import 'package:flutter/material.dart';
import 'package:helloworld/res/depositData.dart';
import 'package:helloworld/res/payData.dart';
import 'package:helloworld/tabs.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'dart:ui';
class AddPay extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _AddPay();
  }
}

class _AddPay extends State<AddPay> with WidgetsBindingObserver {
  Color _textColor;
  String payWay = '请选择';
  int flag = 1;
  int _index = 0;
  var _depositid;
  var _depositcount;
  var _depositnumber;
  var _deposit;
  var _date = TextEditingController();
  var _nameData = TextEditingController();
  DateTime _dateData;
  var _payData = TextEditingController();
  Brightness brightnessValue;
  @override
  void deactivate() {
    // TODO: implement deactivate
    super.deactivate();
    var bool = ModalRoute.of(context).isCurrent;
    if(bool){
      _getData();
    }
  }
  @override
  void didChangePlatformBrightness() {
    // TODO: implement didChangePlatformBrightness
    super.didChangePlatformBrightness();
    if (window.platformBrightness == Brightness.dark) {
      _textColor = Colors.white54;
    } else {
      _textColor = Colors.black54;
    }
  }
  Widget _payWayDialog(){
    if(flag == 1){
      return Container(
        height: 240,
        child: SingleChildScrollView(
          child: Column(
            children: depositData.asMap().keys.map((f) {
              return Column(
                children: <Widget>[
                  Divider(),
                  Container(
                    child: ListTile(
                      title:
                      Text(depositData[f]['depositcount']),
                      subtitle:
                      Text(depositData[f]['depositnumber']),
                      trailing: Text(
                        depositData[f]['deposit'].toString(),
                      ),
                      onTap: () {
                        setState(() {
                          _index = f;
                          payWay = depositData[_index]['depositcount'];
                          Navigator.pop(context);
                        });
                      },
                    ),
                    height: 60,
                  ),
                  // Divider()
                ],
              );
            }).toList(),
          ),
          scrollDirection: Axis.vertical,
        ),
      );
    }else{
      return Center(
        child: Text('暂无存款账户',style: TextStyle(color: _textColor,fontSize: 30),),
      );
    }
  }
  _getData() async {
    Response response =
        await Dio().get("http://123.207.114.127:1314/deposit/selectAll");
    setState(() {
      if(response.data.length==0){
        flag = 0;
      }
      depositData = response.data;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _getData();
    _dateData = DateTime.now();
    _date.text = '${formatDate(_dateData, [mm, '月', dd, '日'])}';
    brightnessValue = window.platformBrightness;
    if (window.platformBrightness == Brightness.dark) {
      _textColor = Colors.white54;
    } else {
      _textColor = Colors.black54;
    }
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('添加支出'),
        actions: <Widget>[
          InkWell(
            child: Padding(
              child: Text(
                '保存',
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
              padding: EdgeInsets.all(16),
            ),
            onTap: () {
              _depositid = depositData[_index]['depositid'];
              _depositcount = depositData[_index]['depositcount'];
              _depositnumber = depositData[_index]['depositnumber'];
              _deposit = depositData[_index]['deposit']-double.parse(_payData.text);
              if(_deposit<0){
                showDialog(context: context,builder: (context){
                  return AlertDialog(
                    content: Text('余额不足',style: TextStyle(fontSize: 20),),
                    actions: <Widget>[
                      FlatButton(
                        child: Text('确定',style: TextStyle(fontSize: 20),),
                        onPressed: (){
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  );
                });
              }else{
                Dio().post("http://123.207.114.127:1314/deposit/updateDeposit",queryParameters: {
                  'depositid':_depositid,
                  'depositcount':_depositcount,
                  'depositnumber':_depositnumber,
                  'deposit': _deposit
                });
                Dio().post("http://123.207.114.127:1314/pay/addPay",
                    queryParameters: {
                      'payname': _nameData.text,
                      'paydate': '${formatDate(_dateData, [mm, '月', dd, '日'])}',
                      'pay': -double.parse(_payData.text),
                      'paymonth': '${formatDate(_dateData, [
                        mm,
                      ])}',
                      'payday': '${formatDate(_dateData, [
                        dd,
                      ])}',
                      'payyear': '${formatDate(_dateData, [
                        yyyy,
                      ])}'
                    });
                Future.delayed(Duration(milliseconds: 50), () {
                  Navigator.of(context).pop();
                  Navigator.of(context).pushAndRemoveUntil(
                      new MaterialPageRoute(
                          builder: (context) => new Tabs(index: 0)),
                          (route) => route == null);
                });
              }
            },
          )
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              InkWell(
                child: Container(
                  decoration: BoxDecoration(
                      border: Border.all(width: 1, color: Colors.grey),
                      borderRadius: BorderRadius.circular(4)),
                  height: 60,
                  width: double.infinity,
                  child: Row(
                    children: <Widget>[
                      SizedBox(
                        width: 10,
                      ),
                      Expanded(
                        flex: 2,
                        child: Text(
                          '付款方式',
                          style: TextStyle(fontSize: 16, color: _textColor),
                        ),
                      ),
                      Expanded(
                        child: Container(
                          child:Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              Text(
                                payWay,
                                style: TextStyle(fontSize: 16, color: _textColor),
                              ),
                              SizedBox(
                                width: 10,
                              ),
                              Icon(
                                Icons.navigate_next,
                                color: _textColor,
                              )
                            ],
                          ),
                          height: 60,
                          // color: Colors.greenAccent,
                        ),
                        flex: 1,
                      )
                    ],
                  ),
                ),
                onTap: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  showDialog(
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                          title: Row(
                            children: <Widget>[
                              Expanded(
                                child: Text("选择支付方式"),
                                flex: 5,
                              ),
                              Expanded(
                                child: IconButton(
                                  icon: Icon(Icons.close),
                                  onPressed: (){
                                    Navigator.pop(context);
                                  },
                                ),
                                flex: 1,
                              )

                            ],
                          ),
                          content: Container(
                            child: _payWayDialog(),
                            // height: 305,
                          ),
                        );
                      });
                },
              ),
              SizedBox(height: 10,),
              TextField(
                keyboardAppearance: brightnessValue,
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '事件'),
                onChanged: (value) {
                  setState(() {
                    _nameData.text = value;
                  });
                },
              ),
              SizedBox(
                height: 10,
              ),
              InkWell(
                child: TextField(
                  controller: _date,
                  enabled: false,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(), labelText: '日期'),
                ),
                onTap: () {
                  DatePicker.showDatePicker(
                    context,
                    onMonthChangeStartWithFirstDate: true,
                    pickerTheme: DateTimePickerTheme(
                      showTitle: true,
                      confirm: Text('确定',
                          style: TextStyle(color: Colors.black54, fontSize: 20)),
                      cancel: Text('取消',
                          style: TextStyle(color: Colors.black54, fontSize: 20)),
                    ),
                    minDateTime: DateTime.parse('2020-01-01'),
                    maxDateTime: DateTime.parse('2099-12-31'),
                    initialDateTime: _dateData,
                    dateFormat: 'MMMM-dd',
                    locale: DateTimePickerLocale.zh_cn,
                    onConfirm: (dateTime, List<int> index) {
                      setState(() {
                        _dateData = dateTime;
                        _date.text =
                        '${formatDate(_dateData, [mm, '月', dd, '日'])}';
                      });
                    },
                  );
                },
              ),
              SizedBox(
                height: 10,
              ),
              TextField(
                keyboardAppearance: brightnessValue,
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '金额'),
                onChanged: (value) {
                  setState(() {
                    _payData.text = value;
                  });
                },
              ),

            ],
          ),
          scrollDirection: Axis.vertical,
        ),
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }
}
